package com.hua.giftool.main.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hua.giftool.BuildConfig
import com.hua.giftool.data.UpdateInfo
import com.hua.giftool.net.api.RequestManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jsoup.Jsoup

class MainViewModel : ViewModel() {

    private val _updateInfo = MutableStateFlow<UpdateInfo?>(null)
    val updateInfo: StateFlow<UpdateInfo?> = _updateInfo

    fun checkForUpdate() {
        viewModelScope.launch {
            try {
                val responseBody = RequestManager.apiService.getAppReleases()
                val html = responseBody.string()

                withContext(Dispatchers.IO) {
                    val document = Jsoup.parse(html)
                    val element = document.select("a[href*=/releases/download/][href$=.apk]").firstOrNull()

                    if (element != null) {
                        val href = element.attr("href")
                        val downloadUrl = "https://gitee.com$href"

                        val regex = Regex(""".*/download/(v[^/]+)/.*""")
                        val matchResult = regex.find(href)
                        val latestVersionName = matchResult?.groups?.get(1)?.value

                        if (latestVersionName != null) {
                            Log.d(
                                "MainViewModel",
                                "Found version: $latestVersionName, current version: ${BuildConfig.VERSION_NAME}"
                            )
                            if (latestVersionName.removePrefix("v") > BuildConfig.VERSION_NAME) {
                                _updateInfo.value = UpdateInfo(latestVersionName, downloadUrl)
                                Log.d("MainViewModel", "Newer version found: $latestVersionName")
                            } else {
                                Log.d("MainViewModel", "App is up to date.")
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                Log.e("MainViewModel", "Failed to check for update", e)
            }
        }
    }
}
